package com.le.tester.book.concurrentjavafight.l7_1;

import org.junit.runner.notification.RunListener;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * createTime：2022/11/3 10:45
 * description：使用volatile来让取消的状态可见
 */
@RunListener.ThreadSafe
public class PrimeGenerator implements Runnable {

    private final List<BigInteger> primes = new ArrayList<>();

    private volatile boolean cancelled;

    @Override
    public void run() {
        BigInteger zero = BigInteger.ZERO;
        BigInteger one = BigInteger.ONE;
        while (!cancelled) {
            one = one.nextProbablePrime();
            synchronized (this) {
                primes.add(one);
            }
        }
    }

    public void cancel() {
        cancelled = true;
    }

    public synchronized List<BigInteger> get() {
        return new ArrayList<>(primes);
    }


    public List<BigInteger> aSecondOfPrimes() throws InterruptedException {
        PrimeGenerator generator = new PrimeGenerator();
        new Thread(generator).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } finally {
            generator.cancel();
        }
        return generator.get();
    }
}
